package org.dromara.visitor.service.impl;

import io.minio.*;
import jakarta.annotation.Resource;
import org.dromara.visitor.service.MinioService;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
public class MinioServiceImpl implements MinioService {
   @Resource
   private MinioClient minioClient;

   private String bucketName = "visitor.pic";

    /**
     * @param objectName 文件路径
     * @param inputStream 文件流
     * @param contentType 文件type
     * @throws Exception
     */
    public String uploadFile(String objectName, InputStream inputStream, String contentType)
        throws Exception {
        // 检查存储桶是否存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder()
            .bucket(bucketName)
            .build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder()
                .bucket(bucketName)
                .build());
        }
        // 设置公共只读策略
        String policyJson = """
            {
              "Version": "2012-10-17",
              "Statement": [
                {
                  "Effect": "Allow",
                  "Principal": "*",
                  "Action": ["s3:GetObject"],
                  "Resource": ["arn:aws:s3:::visitor.pic/*"]
                }
              ]
            }""";
        //设置存储桶可以公共访问
        minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policyJson).build());

        // 上传文件
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(
            PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(inputStream, inputStream.available(), -1)
                .contentType(contentType)
                .build());
        String fullPath = String.format("%s/%s/%s",
            "http://127.0.0.1:9000",
            objectWriteResponse.bucket(),
            objectWriteResponse.object()
        );
       return fullPath;
    }

}
